package com.nus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.nus.database.DBAdaptor;
import com.nus.parsers.ParserAPIs;
import com.nus.representations.IvleLibrary;
import com.nus.representations.IvleTimeTable;
import com.nus.representations.ShuttleMapLocations;

import android.R.integer;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;





public class IvleTimeTableActivity extends Activity{
	private static final int HELLO_ID = 0;
	private ListView lv;
	private ArrayList<IvleTimeTable> timetable;
	public String weekdescription; 
	public String value;
	public ArrayList  week_item = new ArrayList();
	private int rem_hour;
	private int rem_day;
	private int rem_month;
	private int rem_year;
	private int rem_time_to_sub;
	private String rem_location;
	private String rem_desc;
	public String daycode;
	public String venue;
	public String location=null;
	public String module=null, start_time=null;
	public static String location_selected=null;
	 private static final int REQUEST_CODE = 1234;
	 private int flagchk =0;
	 private static StringBuilder total = new StringBuilder();
		public static ArrayList<ShuttleMapLocations> map_t;
		public static String Latitude_item;
		public static String Longitude_item;
		public static String Loc_title;
		protected TextView title;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.ivletimetablelayout);
		 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
		 title = (TextView) findViewById(R.id.titleheader);
		 title.setText("TimeTable");
		 ImageView b = (ImageView)findViewById(R.id.home);
		  b.setImageDrawable(getResources().getDrawable(R.drawable.ivle));
		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/Timetable_Student?APIKey=W7RtgW7GZKUpaEkJ1NwUD&AuthToken="
			+ NUS_Android.IVLE_Token+
			"&AcadYear="+IvleModuleActivity.COURSE_ACAD_YEAR+"&Semester="+IvleModuleActivity.SEMESTER_ID+"&output=json";
		IvleCodeWeekType week_code = new IvleCodeWeekType();
		week_code.getWeekCodeData();
		try {
			String response = getResponseText(url);

			Log.i("Response", response);

			timetable = ParserAPIs.parseIvleTimeTable(response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		lv = (ListView) findViewById(R.id.list_view);
		lv.setAdapter(new ListAdapter(IvleTimeTableActivity.this,
				R.id.time_table, timetable));


	}


	public String getResponseText(String stringUrl) throws IOException {
		StringBuilder response = new StringBuilder();

		URL url = new URL(stringUrl);
		HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
		if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			BufferedReader input = new BufferedReader(new InputStreamReader(
					httpconn.getInputStream()), 8192);
			String strLine = null;
			while ((strLine = input.readLine()) != null) {
				response.append(strLine);
			}
			input.close();
		}
		return response.toString();
	}


	private class ListAdapter extends ArrayAdapter<IvleTimeTable> { // --
		// CloneChangeRequired
		private ArrayList<IvleTimeTable> mList; // --CloneChangeRequired
		private Context mContext;
		String start=null;
	
		
		String week_code=null;
		TextView tv15;
		
       
		public ListAdapter(Context context, int textViewResourceId,
				ArrayList<IvleTimeTable> list) { // --CloneChangeRequired
			super(context, textViewResourceId, list);
			this.mList = list;
			this.mContext = context;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			final View v12 = convertView;
			try {
				if (view == null) {
					LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = vi.inflate(R.layout.ivletimetableitem, null);
				}

				final IvleTimeTable listItem = mList.get(position);

				if (listItem != null) {
					// setting list_item views
					TextView tv14 = (TextView) view.findViewById(R.id.module_code);
					tv14.setText(listItem.getModuleCode());

					TextView tv7 = (TextView) view.findViewById(R.id.type);
					tv7.setText(listItem.getLessonType());

					//					TextView tv8 = (TextView) view.findViewById(R.id.week_type);
					//					tv8.setText(listItem.getWeekText());
					//tv15.setText(
					TextView tv9 = (TextView) view.findViewById(R.id.day);
					tv9.setText(listItem.getDayText());

					TextView tv10 = (TextView) view.findViewById(R.id.start);
					tv10.setText(listItem.getStartTime());
					start=listItem.getStartTime();
					TextView tv11 = (TextView) view.findViewById(R.id.end);
					tv11.setText(listItem.getEndTime());

					final Button bt12 = (Button) view.findViewById(R.id.room);
					bt12.setText(listItem.getVenue());
					IvleTimeTableActivity.location_selected = listItem.getVenue();
					//venue = listItem.getVenue();
					bt12.setOnClickListener(new OnClickListener() {
						
						
						public void onClick(View v) {
							// TODO Auto-generated method stub
							IvleTimeTableActivity.location_selected = ((Button)v).getText().toString();
							Button bt121 = (Button)findViewById(R.id.room);
							//new LocationAPI(bt121.getText().toString());
							Log.i("loc string", bt12.getText().toString());
							location_map(bt121.getText().toString());
						}
					});
					week_code=listItem.getWeekCode();
//					Log.i(" time table"," the week code"+week_code);
					location=listItem.getVenue();
					weekdescription=searchDescription(listItem.getWeekCode());
					tv15=(TextView)view.findViewById(R.id.week_description);
					tv15.setText(weekdescription);
					listItem.getDayCode();
					
				}
			} catch (Exception e) {
				Log.i(IvleTimeTableActivity.ListAdapter.class.toString(), e.getMessage());
			}
			

			Button reminder = (Button)view.findViewById(R.id.reminder_button);
		
			reminder.setOnClickListener(new OnClickListener() {
				//				@Override
			
				String week_desc=null;
				
				
				int min_to_sub;
				
				public void onClick(View v) {
					      
//				   Button tv_room = (Button) v12.findViewById(R.id.room);
					//(id)
					IvleTimeTableActivity.location_selected = ((Button)getCurrentFocus().findViewById(R.id.room)).getText().toString();
				  
					TextView tv123 = (TextView) findViewById(R.id.week_description);
					week_desc=tv123.getText().toString();
					TextView tv1 = (TextView) findViewById(R.id.module_code);
					module=tv1.getText().toString();
					TextView start=(TextView)findViewById(R.id.start);
					start_time=start.getText().toString();
					TextView day=(TextView)findViewById(R.id.day);
					daycode=day.getText().toString();
					Log.i(" time table"," the week desc"+tv15.getText());
					Log.i(" time table"," the week code"+week_code);
					Log.i(" time table","daycode"+daycode);
					if(week_desc.toLowerCase().equalsIgnoreCase("every week") ){
						int start_week_of_semester=25;
						Calendar cal = Calendar.getInstance();
						int current_week=cal.get(Calendar.WEEK_OF_YEAR)+1;
						int nus_week=current_week-start_week_of_semester;
						for(int i=0;i<6;i++){
						week_item.add(nus_week+i);
						}

					}
					else if(week_desc.toLowerCase().equalsIgnoreCase("odd week")) {
						int start_week_of_semester=25;
						Calendar cal = Calendar.getInstance();
						int current_week=cal.get(Calendar.WEEK_OF_YEAR)+1;
						int nus_week=current_week-start_week_of_semester;
						for(int i=1;i<=12;i+=2){
						week_item.add(nus_week+i);
						}

					}
					else if( week_desc.toLowerCase().equalsIgnoreCase("even week")){
						int start_week_of_semester=25;
						Calendar cal = Calendar.getInstance();
						int current_week=cal.get(Calendar.WEEK_OF_YEAR)+1;
						int nus_week=current_week-start_week_of_semester;
						for(int i=2;i<=12;i+=2){
						week_item.add(nus_week+i);
						}

						 
					} else {
						week_item=tokenizeweekdesc(week_desc);
					}

					startVoiceRecognitionActivity();
				
				}
			});

			return view;
		}

	}
	
	
	 private void startVoiceRecognitionActivity()
	    {
	        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
	        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
	                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
	        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "NdroidUS Reminder");
	        startActivityForResult(intent, REQUEST_CODE);
	    }
	 
	    /**
	     * Handle the results from the voice recognition activity.
	     */
	    @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data)
	    {
	        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
	        {
	            // Populate the wordsList with the String values the recognition engine thought it heard
	           final ArrayList<String> matches = data.getStringArrayListExtra(
	                    RecognizerIntent.EXTRA_RESULTS);
	            
	            AlertDialog.Builder builder = new AlertDialog.Builder(this);
	            builder.setMessage("Did you mean this  "+"\""+matches.get(0)+"\"")
	            .setCancelable(false)
	            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int id) {
//	                     MyActivity.this.finish();
	                	Matcher m=null;
	                	Pattern p = Pattern.compile("[0-9]+");
	                	StringTokenizer st= new StringTokenizer(matches.get(0), " ");
	                	while(st.hasMoreTokens()){
	                		String token=st.nextToken();
	                		Log.i("voice","value of token"+token);
	                		m = p.matcher(token);
	                		boolean result=m.find();
	                		Log.i("voice"," value of m.find"+result);
	                	
//	                	Matcher m = p.matcher(matches.get(0));

	                	if (result) {
//	                	    System.out.println(m.group(1));
	                		String value1=token;
	                		reminderHelper(value1);
	                		//setReminder(00,rem_hour , rem_day, rem_month, 2011, rem_location, rem_desc,Integer.parseInt(value1));
	                	  //  Toast.makeText(CareerCenterDetails.this, token, Toast.LENGTH_SHORT).show();
	                	}
	                	}
	                }
	            })
	            .setNegativeButton("Try Again", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int id) {
	                	dialog.cancel();
	                	startVoiceRecognitionActivity();
//	                     dialog.cancel();
	                }
	            });
	     AlertDialog alert = builder.create();
	     alert.show();
//	            wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
//	                    matches));
	        }
	        super.onActivityResult(requestCode, resultCode, data);
	    }
	    
	    public void reminderHelper(String min_to_sub){
			int start_t;
			for( int i=0;i<week_item.size();i++){
				Date d=getDate(week_item.get(i).toString(), daycode);
				Log.i(" time table","date is"+d);
				// write the code for the popup to get the minutes before alerting the user
				if(start_time.length()==3){
				start_t=Integer.parseInt(start_time.substring(0,1));
				}else{
				start_t=Integer.parseInt(start_time.substring(0, 2));	
				}
				String Description=module+"\n"+start_time+"\n"+IvleTimeTableActivity.location_selected;
	            rem_hour = start_t;
	            rem_day = d.getDate();
	            rem_month = d.getMonth();
	            rem_year = 2011;
	            rem_location = IvleTimeTableActivity.location_selected;
	            rem_desc = Description;
	           
				setReminder(00,start_t , d.getDate(), d.getMonth(), 2011, rem_location, Description,Integer.parseInt(min_to_sub));

			}
		}
	    
	public  void setReminder(int mins,int hours,int day,int month,int year,String location,String reminderdesc, int time_to_sub){
		Calendar cal = Calendar.getInstance();
		  DBAdaptor db = new DBAdaptor(this);


		cal.set(Calendar.MONTH, month);
		cal.set(Calendar.YEAR, year);				
		cal.set(Calendar.DAY_OF_MONTH, day);
		cal.set(Calendar.HOUR_OF_DAY, hours);
		cal.set(Calendar.MINUTE, mins);
		time_to_sub = time_to_sub * -1;
		cal.add(Calendar.MINUTE, time_to_sub);
		Date d=cal.getTime();
		Log.i("time table"," time for reminder is"+d);
		Intent alarmintent = new Intent(this, AlarmReceiver.class);
		alarmintent.putExtra("title",cal.getTime().toLocaleString());
		alarmintent.putExtra("note",reminderdesc);
		db.open();
		long id = db.insertRemainder("Reminder",reminderdesc,d.getTime());
		Log.i(" data insertion"," return value are inserting is"+id);
		 db.close();

		//HELLO_ID is a static variable that must be initialised at the BEGINNING OF CLASS with 1;

		//example:protected static int HELLO_ID =1;
		PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), HELLO_ID,
				alarmintent,PendingIntent.FLAG_UPDATE_CURRENT|  Intent.FILL_IN_DATA);
		//VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT... this will send correct extra's informations to 
		//AlarmReceiver Class
		// Get the AlarmManager service

		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
		Context context = getApplicationContext();
		CharSequence text = "Reminder set:"+reminderdesc;
		int duration = Toast.LENGTH_SHORT;

		Toast toast = Toast.makeText(context, text, duration);
		addTocal(cal,reminderdesc);
		toast.show();

	}

	public String searchDescription(String weekcode){
		String description=null;
		for(int i=0;i<IvleCodeWeekType.week_type.size();i++){
			String code=IvleCodeWeekType.week_type.get(i).getWeekCode();
			if(code.equals(weekcode)){
				description=IvleCodeWeekType.week_type.get(i).getDescription();
			}

		}
		return description;
	}

	public ArrayList tokenizeweekdesc(String weekdescription){
		ArrayList week_item=null;
		StringTokenizer tokenizer= new StringTokenizer(weekdescription,",");

		while(tokenizer.hasMoreTokens()){
			week_item.add(tokenizer.nextToken());

		}
		return week_item;
	}

	public Date getDate(String weekdesc, String daycode){
		Date d=null ;
		int year=2011;
		// get semester starting week of the year and add the weekdescription value to it
		int start_week_of_semester=25;
		// add code to tokenise the weekdescription
		Calendar calendar =Calendar.getInstance();
		calendar.clear();
//		calendar.set(Calendar.DAY_OF_WEEK, Integer.parseInt(daycode));
		Log.i(" calendar day is","day code is"+convertdaytocode(daycode));
		calendar.set(Calendar.DAY_OF_WEEK, convertdaytocode(daycode));
		calendar.set(Calendar.YEAR,year);

		calendar.set(Calendar.WEEK_OF_YEAR,start_week_of_semester+Integer.parseInt(weekdesc));

		d=calendar.getTime();
		return d;

	}
	
	public int convertdaytocode(String day){
		int code=0;
		if(day.toLowerCase().equals("sunday")){
			code=1;
		}else if(day.toLowerCase().equals("monday")){
			code=2;
		
		}else if(day.toLowerCase().equals("tuesday")){
			code=3;
		}else if(day.toLowerCase().equals("wednesday")){
			code=4;
		}else if(day.toLowerCase().equals("thursday")){
			code=5;
		}else if(day.toLowerCase().equals("friday")){
			code=6;
		}else {
			code=7;
		}
		
		return code;
	}
	public void location_map(String locationtitle) {	 
	    // if file the available for reading
	  try{
		  Resources res = getResources();
		  InputStream instream = res.openRawResource(R.raw.building1);
		  if (instream != null) {
	      // prepare the file for reading
	      InputStreamReader inputreader = new InputStreamReader(instream);
	      BufferedReader buffreader = new BufferedReader(inputreader);
	     

	      String line;
	 
	      // read every line of the file into the line-variable, on line at the time
	      while (( line = buffreader.readLine()) != null) {
	        // do something with the settings from the file
	    	  total.append(line);
	      }
	      instream.close();
	    }
		String response = total.toString();
		map_t = ParserAPIs.parseShuttleMapLocations(response);
		for (int i = 0; i<map_t.size(); i++) {
			if(locationtitle.equalsIgnoreCase(map_t.get(i).getTitle())){
				Latitude_item = map_t.get(i).getLatitude();
				Longitude_item = map_t.get(i).getLongitude();
				Log.i("inside", Latitude_item);
				flagchk=1;
			}
		}
		if(flagchk==1){
			flagchk=0;
			Intent in = new Intent("com.nus.FindMeInMap");
			in.putExtra("lat",Latitude_item  );
			in.putExtra("long", Longitude_item);
			startActivity(in);
		}
		else
			Toast.makeText( getApplicationContext(), "Unable to find the location", Toast.LENGTH_SHORT ).show();
	  }catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void addTocal(Calendar cal1,String desc){

		String[] projection = new String[] { "_id", "name" };
		Uri calendars = Uri.parse("content://com.android.calendar/calendars");
		     
		String calName; 
		 String calId = null; 
		Cursor managedCursor =
		   managedQuery(calendars, projection,
		   "selected=1", null, null);
		if (managedCursor.moveToFirst()) {
			 
			 int nameColumn = managedCursor.getColumnIndex("name"); 
			 int idColumn = managedCursor.getColumnIndex("_id");
			 do {
			    calName = managedCursor.getString(nameColumn);
			    calId = managedCursor.getString(idColumn);
			 } while (managedCursor.moveToNext());
			}
		
		
		ContentValues event = new ContentValues();
		
		event.put("calendar_id", calId);
		event.put("title", "NUS IVLE");
		event.put("description", desc);
		//event.put("eventLocation", "Event Location");
		long startTime = cal1.getTimeInMillis();
		long endTime = cal1.getTimeInMillis()+60*60*1000;
		event.put("dtstart", startTime);
		event.put("dtend", endTime);
		event.put("allDay", 1); 
		event.put("eventStatus", 1);
		event.put("visibility", 0);
	//	event.put("hasAlarm", 1);
		Uri eventsUri = Uri.parse("content://com.android.calendar/events");
		  Uri url = getContentResolver().insert(eventsUri, event);
		
	}
}


